<template>
  <div class="main">
    <div class="box">
      <div class="choose">
        <div :class="loginOrReg == 0 ? 'itemSelect' : 'item'" @click="loginOrReg = 0">登录</div>
        <div :class="loginOrReg == 1 ? 'itemSelect' : 'item'" @click="loginOrReg = 1">注册</div>
      </div>
      <div class="page">
          <div v-if="loginOrReg == 0">
            <div v-if="loginByName" class="loginForm">
              <el-form :model="loginByNameForm" label-width="auto" style="max-width: 600px">
                <el-form-item label="用户名:">
                  <el-input v-model="loginByNameForm.username"/>
                </el-form-item>
                <el-form-item label="密码:">
                  <el-input v-model="loginByNameForm.password" show-password/>
                </el-form-item>
                <span style="float: right;font-size: 12px;color: #ccc;text-decoration: underline;cursor: pointer;"
                        @click="loginByName=false">
                  使用验证码登录
                </span>
                <el-button type="primary" style="width: 80%;margin-top: 20px;margin-left: 30px;" @click="doLogin">登录</el-button>
              </el-form>
            </div>
            <div v-else class="loginForm">
              <el-form :model="loginByCodeForm" label-width="auto" style="max-width: 600px">
                <el-form-item label="邮箱/手机号:">
                  <el-input v-model="loginByCodeForm.phone" style="width: 80%;" @blur="ruleTest"/>
                </el-form-item>
                <el-form-item label="验证码:" style="display: flex;">
                  <el-input v-model="loginByCodeForm.code" style="width: 45%;" />
                  <div style="width: 50%;margin-left: 3px;">
                    <el-button v-if="showLoginTime==false" @click="sendLoginCode">发送验证码</el-button>
                    <span v-else style="font-size: 12px;">{{ loginTime }}秒后，可以重新发送</span>
                  </div>
                </el-form-item>
                <span style="float: right;font-size: 12px;color: #ccc;text-decoration: underline;cursor: pointer;margin-right: 30px;"
                        @click="loginByName=true">
                  使用密码登录
                </span>
                <el-button type="primary" style="width: 70%;margin-top: 20px;margin-left: 50px;" @click="doLogin">登录</el-button>
              </el-form>
            </div>
          </div>
          <div v-else class="registerForm">
            <el-form :model="loginByCodeForm" label-width="auto" style="max-width: 600px">
                <el-form-item label="用户名:">
                  <el-input v-model="registerForm.username" style="width: 80%;" @blur="nameRule"/>
                </el-form-item>
                <el-form-item v-if="regIsEmail" label="邮箱:">
                  <el-input v-model="registerForm.email" style="width: 80%;" @blur="emailRule"/>
                </el-form-item>
                <el-form-item v-else label="手机号:">
                  <el-input v-model="registerForm.phone" style="width: 80%;" @blur="phoneRule"/>
                </el-form-item>
                <el-form-item label="验证码:" style="display: flex;">
                  <el-input v-model="registerForm.code" style="width: 40%;" />
                  <div style="width: 55%;margin-left: 3px;">
                    <el-button v-if="showRegTime==false" @click="sendRegCode">发送验证码</el-button>
                    <span v-else style="font-size: 12px;">{{ registerTime }}秒后，可以重新发送</span>
                  </div>
                </el-form-item>
                <el-form-item label="密码:">
                  <el-input v-model="registerForm.password" style="width: 80%;" show-password/>
                </el-form-item>
                <span style="float: right;font-size: 12px;color: #ccc;text-decoration: underline;cursor: pointer;margin-right: 30px;"
                        @click="regIsEmail=!regIsEmail">
                  使用{{ regIsEmail?'手机号':'邮箱' }}注册
                </span>
                <el-button type="primary" style="width: 70%;margin-top: 20px;margin-left: 50px;" @click="doReg">注册</el-button>
              </el-form>
          </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import axios from 'axios';
import { ElMessage, ElNotification } from 'element-plus';
import { onBeforeUnmount, reactive, ref, watch } from 'vue';
import {useLoginStore} from '@/stores/LoginStore'
import { useRouter } from 'vue-router';

const router = useRouter()
const logingStore = useLoginStore()

var showLoginTime = ref(false)
var loginOrReg = ref(0)
var loginByName = ref(true)
var loginByNameForm = reactive({
  username:'',
  password:''
})
var loginByCodeForm = reactive({
  phone:'',
  code:''
})
// 验证规则
const ruleTest = () => {
  var value = loginByCodeForm.phone
  const reg = /^1[3-9]\d{9}$/;
  const reg2 = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!(value && !reg.test(value))) {
    return true
  }
  if (!(value && !reg2.test(value))) {
    return true
  }
  ElNotification({
      title:'ERRER',
      message:"请输入正确的邮箱或手机号",
      type:'error',
      duration:1000
    })
  return false
}
var loginTime = ref(180)
var loginTimer:number | undefined = undefined
const sendLoginCode = async () => {
  //校验
  var value = loginByCodeForm.phone
  const reg = /^1[3-9]\d{9}$/;
  const reg2 = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  var header = null
  var url = null
  if(reg.test(value)){
    header = {
      phone:value
    }
    url = "/user/login/sendCode/phone"
  }else{
    if(reg2.test(value)){
      header = {
        email:value
      }
      url = "/user/login/sendCode/email"
    }else{
      ElNotification({
        title:'ERRER',
        message:"请输入正确的邮箱或手机号",
        type:'error',
        duration:1000
      })
      return
    }
  }
  //请求
  var res = await axios.post(
      '/api' + url,
      null,
      {
        headers:header
      }
    )
  console.log(res.data)

  if(res.data.code == 200){
    //开始倒计时
    loginTime.value = 180
    showLoginTime.value = true
    loginTimer = setInterval(() => {
      loginTime.value--
      if(loginTime.value<=0){
        clearInterval(loginTimer)
        showLoginTime.value = false
      }
    }, 1000);
  }else{
    ElNotification({
        title:'ERRER',
        message:res.data.msg,
        type:'error',
        duration:1000
      })
  }
}
// 组件卸载前清除定时器，防止内存泄漏
onBeforeUnmount(() => {
  if (loginTimer) {
    clearInterval(loginTimer);
  }
});
watch(loginOrReg,(newVal,oldVal)=>{
  console.log(newVal)
  if (loginTimer) {
    clearInterval(loginTimer);
  }
  showLoginTime.value = false
  loginByNameForm.password = ''
  loginByNameForm.username = ''
  loginByCodeForm.phone = ''
  loginByCodeForm.code = ''
  registerForm.username = ''
  registerForm.phone = ''
  registerForm.email = ''
  registerForm.password = ''
  registerForm.code = ''
})
watch(loginByName,(newVal,oldVal)=>{
  console.log(newVal)
  if (loginTimer) {
    clearInterval(loginTimer);
  }
  showLoginTime.value = false
  loginByNameForm.password = ''
  loginByNameForm.username = ''
  loginByCodeForm.phone = ''
  loginByCodeForm.code = ''
})
const doLogin = async () => {
  console.log('login')
  var data = null
  var url = null
  if(loginByName.value){
    //用户名登录
    data = {
      username:loginByNameForm.username,
      password:loginByNameForm.password
    }
    url = "/user/login/username"
  }else{
    //验证码登录
    //校验
      var value = loginByCodeForm.phone
      const reg = /^1[3-9]\d{9}$/;
      const reg2 = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if(reg.test(value)){
        console.log('手机号')
        data = {
          phone:value,
          code:loginByCodeForm.code
        }
        url = "/user/login/code"
      }else{
        if(reg2.test(value)){
          console.log('邮箱')
          data = {
            email:value,
            code:loginByCodeForm.code
          }
          url = "/user/login/code"
        }else{
          ElNotification({
            title:'ERRER',
            message:"请输入正确的邮箱或手机号",
            type:'error',
            duration:1000
          })
          return
        }
      }
  }
  console.log(url)
  console.log(data)
  //发送登录请求
  var res = await axios.post('/api'+url,data)
  if(res.data.code == 200){
    ElMessage({
      message:'登录成功',
      type:'success'
    })
    var token = res.data.data.token
    var username = res.data.data.username
    logingStore.setTokenAndUsernaeme(token,username)
    console.log(logingStore.loginToken)
    console.log(logingStore.loginUsername)
    //跳转
    router.push('/')
  }else{
    ElNotification({
            title:'ERRER',
            message:res.data.msg,
            type:'error',
            duration:1000
          })
  }
}

/**
 * 注册表单
 */
var registerForm = reactive({
  username:'',
  phone:'',
  email:'',
  password:'',
  code:''
})
//是否使用邮箱注册
var regIsEmail = ref(true)
watch(regIsEmail,(newVal,oldVal)=>{
  registerForm.email = ''
  registerForm.phone = ''
})
//倒计时
var showRegTime = ref(false)
var registerTime = ref(180)
var registerTimer:number | undefined = undefined
const sendRegCode = async () => {
  var url = ''
  var h = null
  //判断使用什么注册
  if(registerForm.phone == '' && registerForm.email !== ''){
    //判断邮箱格式
    const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if(!reg.test(registerForm.email)){
        ElNotification({
          title:'ERRER',
            message:'邮箱格式错误',
            type:'error',
            duration:1000
        })
        return
    }
    url = '/api/user/register/sendCode/email'
    h = {
        email:registerForm.email
    }
  }else{
    if(registerForm.email == '' && registerForm.phone !== ''){
      //判断手机格式
      const reg = /^1[3-9]\d{9}$/;
      if(!reg.test(registerForm.phone)){
          ElNotification({
            title:'ERRER',
              message:'手机格式错误',
              type:'error',
              duration:1000
          })
          return
      }
      url = '/api/user/register/sendCode/phone'
      h = {
          phone:registerForm.phone
      }
    }else{
      //为空
      ElNotification({
            title:'ERRER',
              message:regIsEmail.value?'邮箱不能为空':'手机号不能为空',
              type:'error',
              duration:1000
      })
      return
    }
  }
  //发送验证码
  var res = await axios.post(url,null,{
    headers:h
  })
  console.log(res.data)
  if(res.data.code == 200){
    ElNotification({
            title:'Success',
              message:'验证码发送成功',
              type:'success',
              duration:1000
          })
    //开始倒计时
    registerTime.value = 180
    showRegTime.value = true
    registerTimer = setInterval(() => {
      registerTime.value--
      if(registerTime.value<=0){
        clearInterval(registerTimer)
        showRegTime.value = false
      }
    }, 1000);
  }else{
    ElNotification({
            title:'ERRER',
              message:res.data.msg,
              type:'error',
              duration:1000
          })
  }
  //开启倒计时
}
//检验用户名
const nameRule = () => {
  var name = registerForm.username
  var errorMsg = null
  // 验证规则
  if (!name) {
    errorMsg = '用户名不能为空'
    ElNotification({
            title:'ERRER',
              message:errorMsg,
              type:'error',
              duration:1000
          })
    return
  }
  
  if (name.length < 3 || name.length > 20) {
    errorMsg = '用户名长度需在3-20个字符之间'
    ElNotification({
            title:'ERRER',
              message:errorMsg,
              type:'error',
              duration:1000
          })
    return
  }
  
  // 允许字母、数字、下划线和连字符
  if (!/^[a-zA-Z0-9_-]{3,20}$/.test(name)) {
    errorMsg = '用户名只能包含字母、数字、下划线和连字符'
    ElNotification({
            title:'ERRER',
              message:errorMsg,
              type:'error',
              duration:1000
          })
    return
  }

}
//检验邮箱
const emailRule = () => {
  //判断邮箱格式
  const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if(!reg.test(registerForm.email)){
        ElNotification({
          title:'ERRER',
            message:'邮箱格式错误',
            type:'error',
            duration:1000
        })
    }
}
//检验手机号
const phoneRule = () => {
  //判断手机格式
  const reg = /^1[3-9]\d{9}$/;
      if(!reg.test(registerForm.phone)){
          ElNotification({
            title:'ERRER',
              message:'手机格式错误',
              type:'error',
              duration:1000
          })
      }
}
//注册
const doReg = async () => {
  var name = registerForm.username
  var errorMsg = null
  // 验证规则
  if (!name) {
    errorMsg = '用户名不能为空'
    ElNotification({
            title:'ERRER',
              message:errorMsg,
              type:'error',
              duration:1000
          })
    return
  }
  
  if (name.length < 3 || name.length > 20) {
    errorMsg = '用户名长度需在3-20个字符之间'
    ElNotification({
            title:'ERRER',
              message:errorMsg,
              type:'error',
              duration:1000
          })
    return
  }
  
  // 允许字母、数字、下划线和连字符
  if (!/^[a-zA-Z0-9_-]{3,20}$/.test(name)) {
    errorMsg = '用户名只能包含字母、数字、下划线和连字符'
    ElNotification({
            title:'ERRER',
              message:errorMsg,
              type:'error',
              duration:1000
          })
    return
  }

  //判断使用什么注册
  if(registerForm.phone == '' && registerForm.email !== ''){
    //判断邮箱格式
    const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if(!reg.test(registerForm.email)){
        ElNotification({
          title:'ERRER',
            message:'邮箱格式错误',
            type:'error',
            duration:1000
        })
        return
    }
  }else{
    if(registerForm.email == '' && registerForm.phone !== ''){
      //判断手机格式
      const reg = /^1[3-9]\d{9}$/;
      if(!reg.test(registerForm.phone)){
          ElNotification({
            title:'ERRER',
              message:'手机格式错误',
              type:'error',
              duration:1000
          })
          return
      }
    }else{
      //为空
      ElNotification({
            title:'ERRER',
              message:regIsEmail.value?'邮箱不能为空':'手机号不能为空',
              type:'error',
              duration:1000
      })
      return
    }
  }
  if(registerForm.code == ''){
    ElNotification({
            title:'ERRER',
              message:'验证码不能为空',
              type:'error',
              duration:1000
      })
      return
  }
  if(registerForm.password == ''){
    ElNotification({
            title:'ERRER',
              message:'密码不能为空',
              type:'error',
              duration:1000
      })
      return
  }
  //发送请求
  var res = await axios.post('/api/user/register',registerForm)
  if(res.data.code == 200){
    ElNotification({
            title:'Success',
              message:'注册成功',
              type:'success',
              duration:1000
      })
    loginOrReg.value = 0
  }else{
    ElNotification({
            title:'ERROR',
              message:res.data.msg,
              type:'error',
              duration:1000
      })
  }
}
</script>
<style scoped>
.main{
  background: url('/src/assets/images/login_bg.jpg');
  height: 460px;
  display: flex;
  justify-content: end;
  align-items: center;
}
.box{
  height: 80%;
  width: 350px;
  background-color: #fff;
  margin-right: 100px;
  border-radius: 10px;
}
.choose{
  display: flex;
  justify-content: space-around;
  height: 39px;
  border-bottom: 1px solid #ccc;
  width: 70%;
  margin: 0 auto;
}
.item{
  width: 30%;
  font-size: 24px;
  height: 40px;
  text-align: center;
  cursor: pointer;
}
.itemSelect{
  width: 30%;
  font-size: 24px;
  height: 38px;
  color: red;
  border-bottom: 2px solid red;
  text-align: center;
  cursor: pointer;
}
.page{
  height: 310px;
}
.loginForm{
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 50px;
}
.no-border-input .el-input__inner {
  border: none;
  outline: none;
}
.registerForm{
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30px;
  padding-left: 50px;
}
</style>